# -*- coding:utf-8 -*-

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from config import DevelopmentConfig as DC
from app import db
from app.models.statistic import Addition, Daily_Statistic as DS
import datetime

engine = create_engine(DC.SQLALCHEMY_DATABASE_URI)
Session = sessionmaker(bind=engine)
session = Session()

'''
每天0点会自动运行这个脚本，用于统计前一日新增的各类申请
start用于指定统计的日期(字符串类型)，默认为当前日期的前一天
redo用于指定当某一日期的统计结果已经存在时，是否删除该结果并重新进行统计
'''
def stats(start=None, redo=False):
	if not start:
		start = datetime.date.today() - datetime.timedelta(days=1)
	else:
		start = datetime.datetime.strptime(start, "%Y-%m-%d").date()
	end = start + datetime.timedelta(days=1)
	dss = session.query(DS).filter_by(date=start).all()
	if dss:
		if redo:
			for item in dss:
				session.delete(item)
			session.commit()
		else:
			return
	stats_type = ['rent', 'buy', 'finance', 'service', 'account', 'car', 'loan']
	user_type = [1, 2]
	source = [0, 1]
	month = str(start.year) + str(start.month)
	for st in stats_type:
		for ut in user_type:
			for s in source:
				count = session.query(Addition).filter_by(add_type=st, user_type=ut, source=s).filter(Addition.date.between(start, end)).count()
				ds = DS(count=count, user_type=ut, source=s, stats_type=st, date=start, month=month)
				session.add(ds)
	session.commit()
	return 

if __name__ == '__main__':
	stats()
	print u'统计完成'
